import { editMenuData, createMenuData, deleteMenuById, postMenuListData } from '@/service/menu/menu'
import type { IMenuList } from '@/types/menu/menu'
import { notification } from '@/utils/notification'
import { defineStore } from 'pinia'

const useMenuStore = defineStore('menu', {
  state: () => ({
    menuList: [] as IMenuList[],
    totalCount: 0
  }),
  actions: {
    // 菜单列表
    async postMenuListDataAction(data?: any) {
      // 1.获取菜单列表数据
      const menuListRes = await postMenuListData(data)

      // 2.存储菜单列表数据
      const { list, totalCount } = menuListRes.data
      this.menuList = list
      this.totalCount = totalCount
    },
    // 删除菜单
    async deleteMenuByIdAction(id: number) {
      // 1.调用接口
      const deletemenuRes = await deleteMenuById(id)

      // 2.消息提示
      if (deletemenuRes.code === 0) {
        // 2.1删除成功
        notification('success', deletemenuRes.data)
        // 2.2请求新的数据
        this.postMenuListDataAction({ size: 10, offset: 0 })
      } else {
        //2.3删除失败
        notification('error', deletemenuRes.data)
      }
    },
    // 新建菜单
    async createMenuDataAction(userInfo: any) {
      // 1.调用接口
      const createmenuRes = await createMenuData(userInfo)

      // 2.消息提示
      if (createmenuRes.code === 0) {
        // 2.1新建成功
        notification('success', createmenuRes.data)
        // 2.2请求新的数据
        this.postMenuListDataAction({ size: 10, offset: 0 })
      } else {
        //2.3新建失败
        notification('error', createmenuRes.data)
      }
    },
    //编辑菜单
    async editMenuDataAction(id: number, userInfo: any) {
      // 1.调用接口
      const editmenuRes = await editMenuData(id, userInfo)
      // 2.消息提示
      if (editmenuRes.code === 0) {
        // 2.1编辑成功
        notification('success', editmenuRes.data)
        // 2.2请求新的数据
        this.postMenuListDataAction({ size: 10, offset: 0 })
      } else {
        //2.3编辑失败
        notification('error', editmenuRes.data)
      }
    }
  }
})

export default useMenuStore
